'use client';

import React, { useState, useEffect, useMemo } from 'react';
import { ChevronDownIcon, MagnifyingGlassIcon, HomeIcon, ArrowLeftIcon } from '@heroicons/react/24/outline';
import { useMultipleMarketData } from '../hooks/useMarketData';
import Link from 'next/link';

interface TokenPair {
  symbol: string;
  name: string;
  price: number;
  change24h: number;
  volume24h: number;
  icon?: string;
}

interface TradingHeaderProps {
  currentPair: TokenPair;
  onPairChange: (pair: TokenPair) => void;
}

const availablePairs = [
  { symbol: 'BTCUSDT', name: 'Bitcoin', displaySymbol: 'BTC/USDT' },
  { symbol: 'ETHUSDT', name: 'Ethereum', displaySymbol: 'ETH/USDT' },
  { symbol: 'SOLUSDT', name: 'Solana', displaySymbol: 'SOL/USDT' },
  { symbol: 'ADAUSDT', name: 'Cardano', displaySymbol: 'ADA/USDT' },
  { symbol: 'DOTUSDT', name: 'Polkadot', displaySymbol: 'DOT/USDT' },
];

export default function TradingHeader({ 
  currentPair, 
  onPairChange
}: TradingHeaderProps) {
  const [showPairSelector, setShowPairSelector] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [filteredPairs, setFilteredPairs] = useState(availablePairs);

  // 使用 useMemo 来稳定化 symbols 数组，避免无限重新渲染
  const symbols = useMemo(() => availablePairs.map(p => p.symbol), []);

  // 获取多个交易对的实时数据
  const { data: marketData, loading } = useMultipleMarketData(
    symbols,
    'binance'  // 使用币安真实数据
  );

  // 处理搜索过滤
  useEffect(() => {
    const filtered = availablePairs.filter(pair => 
      pair.displaySymbol.toLowerCase().includes(searchQuery.toLowerCase()) ||
      pair.name.toLowerCase().includes(searchQuery.toLowerCase())
    );
    setFilteredPairs(filtered);
  }, [searchQuery]);

  // 将原始数据转换为TokenPair格式
  const convertToTokenPair = (pairInfo: typeof availablePairs[0]): TokenPair => {
    const stats = marketData[pairInfo.symbol];
    if (stats) {
      return {
        symbol: pairInfo.displaySymbol,
        name: pairInfo.name,
        price: parseFloat(stats.lastPrice),
        change24h: parseFloat(stats.priceChangePercent),
        volume24h: parseFloat(stats.quoteVolume),
      };
    }
    
    // 返回默认值如果没有数据
    return {
      symbol: pairInfo.displaySymbol,
      name: pairInfo.name,
      price: 0,
      change24h: 0,
      volume24h: 0,
    };
  };

  const formatVolume = (volume: number) => {
    if (volume >= 1e9) return `$${(volume / 1e9).toFixed(1)}B`;
    if (volume >= 1e6) return `$${(volume / 1e6).toFixed(1)}M`;
    if (volume >= 1e3) return `$${(volume / 1e3).toFixed(1)}K`;
    return `$${volume.toLocaleString()}`;
  };

  return (
    <div className="bg-white dark:bg-[#1E2026] border-b border-gray-200 dark:border-gray-700 px-6 py-4">
      <div className="flex items-center justify-between">
        {/* 左侧：返回首页 + 交易对选择 */}
        <div className="flex items-center space-x-4">
          {/* 返回首页按钮 */}
          <Link 
            href="/"
            className="flex items-center space-x-2 text-gray-600 hover:text-gray-900 dark:text-gray-400 dark:hover:text-white transition-colors group"
          >
            <ArrowLeftIcon className="w-5 h-5" />
            <HomeIcon className="w-5 h-5" />
            <span className="hidden sm:inline text-sm font-medium">返回首页</span>
          </Link>

          {/* 分割线 */}
          <div className="w-px h-8 bg-gray-200 dark:bg-gray-600"></div>

          {/* 交易对选择 */}
          <div className="relative">
            <button
              onClick={() => setShowPairSelector(!showPairSelector)}
              className="flex items-center space-x-2 text-left hover:bg-gray-50 dark:hover:bg-gray-700 px-3 py-2 rounded-lg transition-colors"
            >
              <div>
                <div className="text-lg font-semibold text-gray-900 dark:text-white">
                  {currentPair.symbol}
                </div>
                <div className="text-sm text-gray-500 dark:text-gray-400">
                  {currentPair.name}
                </div>
              </div>
              <ChevronDownIcon className="w-5 h-5 text-gray-400" />
            </button>

            {/* 交易对选择面板 */}
            {showPairSelector && (
            <div className="absolute top-full left-0 mt-1 w-96 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg z-50">
              <div className="p-4">
                {/* 搜索框 */}
                <div className="relative mb-4">
                  <MagnifyingGlassIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
                  <input
                    type="text"
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    placeholder="搜索交易对..."
                    className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                </div>

                {/* 分类标签 */}
                <div className="flex space-x-2 mb-4">
                  <button className="px-3 py-1 text-sm bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 rounded-full">
                    热门
                  </button>
                  <button className="px-3 py-1 text-sm bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-full">
                    稳定币
                  </button>
                  <button className="px-3 py-1 text-sm bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-full">
                    自选
                  </button>
                </div>

                {/* 交易对列表 */}
                <div className="max-h-64 overflow-y-auto">
                  {filteredPairs.map((pairInfo) => {
                    const pair = convertToTokenPair(pairInfo);
                    return (
                      <button
                        key={pairInfo.symbol}
                        onClick={() => {
                          onPairChange(pair);
                          setShowPairSelector(false);
                        }}
                        className="w-full flex items-center justify-between p-3 hover:bg-gray-50 dark:hover:bg-gray-700 rounded-lg transition-colors"
                      >
                        <div className="flex items-center space-x-3">
                          <div className="w-8 h-8 bg-gray-200 dark:bg-gray-600 rounded-full flex items-center justify-center">
                            <span className="text-xs font-semibold text-gray-600 dark:text-gray-300">
                              {pair.symbol.split('/')[0].slice(0, 2)}
                            </span>
                          </div>
                          <div className="text-left">
                            <div className="font-medium text-gray-900 dark:text-white">
                              {pair.symbol}
                            </div>
                            <div className="text-sm text-gray-500 dark:text-gray-400">
                              {pair.name}
                            </div>
                          </div>
                        </div>
                        <div className="text-right">
                          <div className="font-medium text-gray-900 dark:text-white">
                            ${pair.price > 0 ? pair.price.toLocaleString() : 'Loading...'}
                          </div>
                          <div className={`text-sm ${
                            pair.change24h >= 0 
                              ? 'text-green-600 dark:text-green-400' 
                              : 'text-red-600 dark:text-red-400'
                          }`}>
                            {pair.change24h >= 0 ? '+' : ''}{pair.change24h.toFixed(2)}%
                          </div>
                        </div>
                      </button>
                    );
                  })}
                  
                  {!loading && filteredPairs.length === 0 && (
                    <div className="text-center py-4 text-gray-500 dark:text-gray-400">
                      没有找到匹配的交易对
                    </div>
                  )}
                  
                  {loading && (
                    <div className="text-center py-4 text-gray-500 dark:text-gray-400">
                      加载中...
                    </div>
                  )}
                </div>
              </div>
            </div>
          )}
          </div>
        </div>

        {/* 价格展示区 */}
        <div className="flex items-center space-x-8">
          <div>
            <div className="text-2xl font-bold text-gray-900 dark:text-white">
              ${currentPair.price.toLocaleString()}
            </div>
            <div className="text-sm text-gray-500 dark:text-gray-400">
              最新价格
            </div>
          </div>
          <div>
            <div className={`text-lg font-semibold ${
              currentPair.change24h >= 0 
                ? 'text-green-600 dark:text-green-400' 
                : 'text-red-600 dark:text-red-400'
            }`}>
              {currentPair.change24h >= 0 ? '+' : ''}{currentPair.change24h}%
            </div>
            <div className="text-sm text-gray-500 dark:text-gray-400">
              24h 变动
            </div>
          </div>
          <div>
            <div className="text-lg font-semibold text-gray-900 dark:text-white">
              {formatVolume(currentPair.volume24h)}
            </div>
            <div className="text-sm text-gray-500 dark:text-gray-400">
              24h 成交量
            </div>
          </div>
        </div>
      </div>

      {/* 点击外部关闭选择器 */}
      {showPairSelector && (
        <div
          className="fixed inset-0 z-40"
          onClick={() => setShowPairSelector(false)}
        />
      )}
    </div>
  );
}
